<?php

class Jd
{
    public $data = [];

    private $union;
    /**
     * 订单状态转换
     * 0    默认 1    待支付 2    已支付 3    已退款 4    已完成 5    已失效 6    已结算 11    已取消
     *（-1：未知 2.无效-拆单 3.无效-取消 4.无效-京东帮帮主订单 5.无效-账号异常 6.无效-赠品类目不返佣 7.无效-校园订单 8.无效-企业订单 9.无效-团购订单 10.无效-开增值税专用发票订单 11.无效-乡村推广员下单 12.无效-自己推广自己下单 13.无效-违规订单 14.无效-来源与备案网址不符 15.待付款 16.已付款 17.已完成 18.已结算（5.9号不再支持结算状态回写展示））注：自2018/7/13起，自己推广自己下单已经允许返佣，故12无效码仅针对历史数据有效
     * sku维度的有效码（
     * -1：未知,
     * 2.无效-拆单,
     * 3.无效-取消,
     * 4.无效-京东帮帮主订单,
     * 5.无效-账号异常,
     * 6.无效-赠品类目不返佣,
     * 7.无效-校园订单,
     * 8.无效-企业订单,
     * 9.无效-团购订单,
     * 10.无效-开增值税专用发票订单,
     * 11.无效-乡村推广员下单,
     * 13.无效-违规订单,
     * 14.无效-来源与备案网址不符,
     * 15.待付款,
     * 16.已付款,
     * 17.已完成,
     * 18.已结算（5.9号不再支持结算状态回写展示））
     */
    private $status = [
        3 => "11",
        15 => "1",
        16 => "2",
        17 => "6",
        18 => "6",
    ];

    private $jiruan=[
        'appKey' => '79ab36193d1acde1c7361d07c6e124b6',//
        'appSecret' => '1167f168d96b48d1a21911361b78adc2',//
    ];
    public function __construct($union)
    {
        $this->union = $union;
    }


    //公共查询lx
    public function public_query($method, $params = [])
    {
        $secret                      = $this->union['appSecret'];
        $public_params               = [
            'v'           => '1.0',
            'method'      => $method,
            'app_key'     => $this->union['appKey'],
            'sign_method' => 'md5',
            'format'      => 'json',
            'timestamp'   => date('Y-m-d H:i:s'),
        ];
        $public_params['param_json'] = $params;
        $public_params['sign']       = $this->sign($public_params, $secret);
        $url                         = 'https://router.jd.com/api' . '?' . http_build_query($public_params);
        $res                         = file_get_contents($url);
        $res                         = json_decode($res, true);
        if (array_key_exists('error_response', $res)) {
            header('Content-Type:application/json');
            $data['code'] = -1; 
            $data['msg']  = $res['error_response']['zh_desc'];
            echo json_encode($data, 1);
            exit();

        }
        return $res;
    }




    //公共查询公司
    public function public_query_jiruan($method, $params = [])
    {
        $secret                      = $this->jiruan['appSecret'];
        $public_params               = [
            'v'           => '1.0',
            'method'      => $method,
            'app_key'     => $this->jiruan['appKey'],
            'sign_method' => 'md5',
            'format'      => 'json',
            'timestamp'   => date('Y-m-d H:i:s'),
        ];
        $public_params['param_json'] = $params;
        $public_params['sign']       = $this->sign($public_params, $secret);
        $url                         = 'https://router.jd.com/api' . '?' . http_build_query($public_params);
        $res                         = file_get_contents($url);
        $res                         = json_decode($res, true);
        if (array_key_exists('error_response', $res)) {
            header('Content-Type:application/json');
            $data['code'] = -1;
            $data['msg']  = $res['error_response']['zh_desc'];
            echo json_encode($data, 1);
            exit();

        }
        return $res;
    }


    public function curlRequestForPost($url, $post_data)
    {
        if (is_array($post_data)) {
            $post_data = http_build_query($post_data);
        }

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        // 20s 超时
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($curl, CURLOPT_TIMEOUT, 20);

        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        // post参数
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        $list_stat = curl_exec($curl);

        // curl 出错
        if (curl_errno($curl)) {
            return [
                'success' => false,
                'msg'     => curl_error($curl)
            ];
        }
        curl_close($curl);
        return $list_stat;
    }


    //签名方法
    protected function sign(array $params, $secret)
    {
        ksort($params);
        $str = '';
        foreach ($params as $name => $value) {
            $str .= "{$name}{$value}";
        }
        return strtoupper(md5(implode('', [$secret, $str, $secret])));
    }

    //公共列表转换
    public function trun_list($res, $code = 0)
    {
//	京东优惠券	$res=$res[0]['couponInfo'];
        $data = [];
        $site = "jd";
        foreach ($res as $k => $v) {
            $arr             = [
                "GoodsId"    => "{$v['skuId']}",
                "Title"      => $v['skuName'],
                "ShortTitle" => $v['skuName'],
                "ShopType"   => "京东",
                "PicLogo" => $v['imageInfo']['imageList'][0]['url'],
                "Couponurl" => isset($v['couponInfo']['couponList'][0]['link']) ? $v['couponInfo']['couponList'][0]['link'] : "",
                "CouponMoney"   => $v['couponInfo']['couponList'] == [] ? 0 : $v['couponInfo']['couponList'][0]['discount'],
                "CouponSurplus" => $v['couponInfo']['couponList'] == [] ? 0 : rand(10, 9999),
                "Price"         => $v['priceInfo']['price'],
                "EndPrice"   => isset($v['priceInfo']['lowestPrice']) ? $v['priceInfo']['lowestPrice'] : $v['priceInfo']['price'],
                "Commission" => $v['commissionInfo']['commission'],
                "MonthSale"  => rand(999, 10000),
                "Site"       => $site,
                "ShopName"   => $v['shopInfo']['shopName'],
                "CouponTotal"=> "0",
                "VideoUrl" => "",
                "ItemFrom" => "jd",
            ];
            $arr['EndPrice'] = $arr['EndPrice'] - $arr['CouponMoney'];
            //如果有佣金比例，就算
            if ($v['commissionInfo']['commissionShare']) {
                $arr['Commission'] = $arr['EndPrice'] * $v['commissionInfo']['commissionShare'] / 100;
            }
            //京粉 最后价格处理
            if ($code == 2) {
                $discount = $v['couponInfo']['couponList'] == [] ? 0 : $v['couponInfo']['couponList'][0]['discount'];
                if ($discount) {
                    $arr['EndPrice'] = $v['priceInfo']['price'] - $discount;
                }
            }

            $data[] = $arr;
        }
        return $data;
    }

//商品列表
    public function goods_list($params)
    {
        $h_params = [];
        if (!in_array($params['category_id'],[1,-1])) {
            $h_params['cid1'] = $params['category_id'];
        };
        if ($params['page_size']) {
            $h_params['pageSize'] = $params['page_size'];
        } else {
            $h_params['pageSize'] = 10;
        }
        if ($params['page']) {
            $h_params['pageIndex'] = $params['page'];
        } else {
            $h_params['back'] = 10;
        }
        if ($params['order_by']) {
            $h_params['sortName1'] = $params['order_by'];
        };
        if ($params['sort']) {
            $h_params['sort'] = $params['sort'];
        }
        if ($params['is_compoon']) {
            $h_params['isCoupon'] = $params['is_compoon'];
        }
        ksort($h_params);
        $key    = 'jd.union.open.goods.query';
        $params = json_encode(['goodsReqDTO' => $h_params]);
        $res    = $this->public_query_jiruan($key, $params);
        $res    = json_decode($res['jd_union_open_goods_query_response']['result'], true);
        if($res['code'] != 200){
            return ['status'=>false,'msg'=>$res['msg'],'data'=>[]];
        }
        $responseResult['status'] = true;
        $responseResult['msg'] = "获取成功";
        $responseResult['data'] = $this->trun_list($res['data']);
        return $responseResult;
    }

    //商品详情
    public function goods_detail($goods_id)
    {
        $params['apikey']    = '9f5c1a28acb2939c';
        $params['goods_ids'] = $goods_id;

        $url = 'http://api-gw.haojingke.com/index.php/v1/api/jd/goodslist' . '?' . http_build_query($params);
        $res = json_decode(file_get_contents($url), true);
        if ($res['status_code'] != 200) {
            return ['status'=>false,'msg'=>$res['message']];
        }
        if ($res['data']['total'] == 0) {
            return ['status'=>false,'msg'=>'商品不存在'];
        }
        $res  = $res['data']['data'][0];
        $site = 'jd';
        $arr  = [
            "GoodsId"    => $res['goods_id'],
            "Title"      => $res['goods_name'],
            "ShortTitle" => $res['goods_short_name'],
            "ShopType"   => "京东",
            "PicLogo" => $res['picurl'],
            'Suggest' => $res['goods_desc'],
            'Couponurl'       => isset($res['couponurl']) ? $res['couponurl'] : '',
            'CouponStartTime' => date('Y-m-d',$res['start_time']),//strtotime($res['start_time']) ? $res['start_time'] : 0,
            'CouponEndTime'   => date('Y-m-d',$res['end_time']),//strtotime($res['end_time']) ? $res['end_time'] : 0,
            "CouponMoney"   => $res['discount'],
            "CouponSurplus" => rand(99, 1000),
            "Price"         => $res['price'],
            "EndPrice"      => $res['price_after'],
            "Commission"    => $res['price_after'] * $res['commissionshare'] / 100,
            "MonthSale"     => $res['sales'],
            "Site"          => $site,
            'PicList'       => $res['picurls'] ? explode(",", $res['picurls']) : [],
            'SmallImages'   => [],
            'VideoUrl'      => '',
            "ShopName"      => $res['shopname'],
            "ShopId"        => $res['shopid'],
            "ShopUrl"       => '',
            "ShopIcon"      => '',
            "DescTxt"       => sprintf("%.2f", round(4.9, 2)),
            "ServTxt"       => sprintf("%.2f", round(4.9, 2)),
            "AvgTxt"        => sprintf("%.2f", round(4.9, 2)),
        ];
        return ['status'=>true,'msg'=>'获取成功','data'=>$arr];
    }


    //商品搜索
    public function goods_search($params)
    {
        $params['keyword'] = trim(urldecode($params['keyword']));
        $h_params          = [];
        if ($params['keyword']) {
            $h_params['keyword'] = $params['keyword'];
        }
        if ($params['page_size']) {
            $h_params['pageSize'] = $params['page_size'];
        } else {
            $h_params['pageSize'] = 10;
        }
        if ($params['page']) {
            $h_params['pageIndex'] = $params['page'];
        } else {
            $h_params['back'] = 10;
        }

        if ($params['order_by']) {
            if ($params['order_by'] == 'price' && $params['sort'] == 'asc') {
                $h_params['sortName'] = 'price';
                $h_params['sort']     = 'asc';
            }
            if ($params['order_by'] == 'price' && $params['sort'] == 'desc') {
                $h_params['sortName'] = 'price';
                $h_params['sort']     = 'desc';
            }
            if ($params['order_by'] == 'sale' && $params['sort'] == 'desc') {
                $h_params['sortName'] = 'inOrderCount30Days';
                $h_params['sort']     = 'desc';
            }
            if ($params['order_by'] == 'sale' && $params['sort'] == 'asc') {
                $h_params['sortName'] = 'inOrderCount30Days';
                $h_params['sort']     = 'asc';
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'desc') {
                $h_params['sortName'] = 'commission';
                $h_params['sort']     = 'desc';
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'asc') {
                $h_params['sortName'] = 'commission';
                $h_params['sort']     = 'asc';
            }
        };
        //$h_params['isCoupon']=1;
        ksort($h_params);
        $key     = 'jd.union.open.goods.query';
        $params1 = json_encode(['goodsReqDTO' => $h_params]);
        $res     = $this->public_query_jiruan($key, $params1);
        $res     = json_decode($res['jd_union_open_goods_query_response']['result'], true);
        $responseResult = ['status'=>false,'msg'=>'获取失败','data'=>[]];
        //如果搜不出来
        if (!isset($res['data'])) {
            $a                   = explode(" ", $h_params['keyword']);
            $h_params['keyword'] = $a[0];
            if (count($a) > 1 && mb_strlen($h_params['keyword']) < 10) {
                $h_params['keyword'] .= ' ' . $a[1];
            }
            ksort($h_params);
            $key    = 'jd.union.open.goods.query';
            $params = json_encode(['goodsReqDTO' => $h_params]);
            $res    = $this->public_query_jiruan($key, $params);
            $res    = json_decode($res['jd_union_open_goods_query_response']['result'], true);
            if(isset($res['data'])){
                $data =$this->trun_list($res['data']);
                $responseResult['status'] = true;
                $responseResult['data'] = $data;
            }
        }else{
            $data =$this->trun_list($res['data']);
            $responseResult['status'] = true;
            $responseResult['data'] = $data;
        }
        return $responseResult;
    }


    /**
     * @param $params 获取京粉详情
     */
    public function jd_querygoods($params)
    {
        if ($params['eliteId']) {
            $h_params['eliteId'] = $params['eliteId'];
        } else {
            $h_params['eliteId'] = 22;
        }
        if ($params['pageSize']) {
            $h_params['pageSize'] = $params['pageSize'];
        } else {
            $h_params['pageSize'] = 10;
        }
        if ($params['page']) {
            $h_params['pageIndex'] = $params['page'];
        } else {
            $h_params['pageIndex'] = 1;
        }
        if ($params['order_by']) {
            if ($params['order_by'] == 'price' && $params['sort'] == 'asc') {
                $h_params['sortName'] = 'price';
                $h_params['sort']     = 'asc';
            }
            if ($params['order_by'] == 'price' && $params['sort'] == 'desc') {
                $h_params['sortName'] = 'price';
                $h_params['sort']     = 'desc';
            }
            if ($params['order_by'] == 'comments' && $params['sort'] == 'desc') {
                $h_params['sortName'] = 'comments';
                $h_params['sort']     = 'desc';
            }
            if ($params['order_by'] == 'comments' && $params['sort'] == 'asc') {
                $h_params['sortName'] = 'comments';
                $h_params['sort']     = 'asc';
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'desc') {
                $h_params['sortName'] = 'commission';
                $h_params['sort']     = 'desc';
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'asc') {
                $h_params['sortName'] = 'commission';
                $h_params['sort']     = 'asc';
            }
            if ($params['order_by'] == 'goodComments' && $params['sort'] == 'desc') {
                $h_params['sortName'] = 'goodComments';
                $h_params['sort']     = 'desc';
            }
        }
        ksort($h_params);
        $key    = 'jd.union.open.goods.jingfen.query';
        $params = json_encode(['goodsReq' => $h_params]);
        $res    = $this->public_query_jiruan($key, $params);
        if ($res['jd_union_open_goods_jingfen_query_response']['code'] == 0) {
            $res = json_decode($res['jd_union_open_goods_jingfen_query_response']['result'], true);
            $res = $res['data'];
            $res = $this->trun_list($res, $code = 2);
            return $res;
        }
        return false;
    }


    /**
     * @param $user_id 用户id
     * @param $goods_id 商品id
     * @return array
     */
    public function createturn($user_id, $goods_id, $couponurl = '')
    {
        $mothed                 = 'jd.union.open.promotion.bysubunionid.get';
        $h_params['materialId'] = 'https://wqitem.jd.com/item/view?sku=' . $goods_id;
        $h_params['subUnionId'] = $user_id;
        $h_params['chainType']  = 3;
        $h_params['couponUrl']  = $couponurl;
        ksort($h_params);
        $params = json_encode(['promotionCodeReq' => $h_params]);
        $res    = $this->public_query($mothed, $params);
        if ($res['jd_union_open_promotion_bysubunionid_get_response']['code'] == 0) {
            $ret = json_decode($res['jd_union_open_promotion_bysubunionid_get_response']['result']);
            if ($ret->code == 200) {
                return ['status' => true, 'msg' => $ret->data->clickURL, 'short_url' => $ret->data->shortURL];
            } else {
                return ['status' => false, 'msg' => $ret->message];
            }
        } else {
            return ['status' => false, 'msg' => '请求失败'];
        }
    }


    /**
     * 订单处理
     */
    private function returnOrderDeal($data)
    {
        $tempResponseMsgResult = [];
        foreach ($data as $k => $v) {
            foreach ($v['skuList'] as $k1 => $v1) {
                $v1['orderId'] = "{$v['orderId']}-{$v1['skuNum']}-{$v1['skuId']}";
                $v1['payMonth'] = $v['payMonth'];
                $v1['orderTime'] = $v['orderTime'];
                $v1['finishTime'] = $v['finishTime'];
                $tempResponseMsgResult["{$v['orderId']}-{$v1['skuNum']}-{$v1['skuId']}"] = $v1;
            }
        }
        $responseMsgResult = [];
        foreach($tempResponseMsgResult as $key=>$v1){
            $order_id = $v1['orderId'];
            $order_status = in_array($v1['validCode'], ["3", "15", "16", "17", "18"]) ? $this->status[$v1['validCode']] : 11;
            $userId = isset($v1['positionId']) ? $v1['positionId'] : 0;
            $goodsDetail = $this->goods_detail($v1['skuId']);
            $turnData = [
                'orderId' => $order_id,
                'orderStatus' => $order_status,
                'site' =>'jd',
                'orderSrc' => 2,
                'tag' => '京东',
                'tagItem' => '京东',
                'name' => $v1['skuName'],
                'goodsId' => $v1['skuId'],
                'images' => $goodsDetail['status'] ? $goodsDetail['data']['PicLogo'] : '',
                'rid' => $userId,
                'shopName' => $goodsDetail['status'] ? $goodsDetail['data']['ShopName'] : '',
                'price' => $v1['price'],
                'orderType' => in_array($order_status,[2,6]) ? 1 : 4,
                'payMoney' => $v1['actualCosPrice'] > 0 ? $v1['actualCosPrice'] : $v1['estimateCosPrice'],
                'rebateAmount' => $v1['actualFee'] > 0 ? $v1['actualFee'] : $v1['estimateFee'],
                'incomeRate' => $v1['commissionRate'],
                'orderCreateTime' => $v1['orderTime'] != 0 ? date("Y-m-d H:i:s", (int)($v1['orderTime'] / 1000)) : null,
                'orderPaidTime' => $order_status > 1 ? date("Y-m-d H:i:s", (int)($v1['orderTime'] / 1000)) : null,
                //'orderEarningTime' => $v['payMonth'] != 0 ? substr($v['payMonth'], 0, 4) . '-' . substr($v['payMonth'], 4, 2) . '-' . substr($v['payMonth'], -2) . ' 00:00:00' : null,
                'orderEarningTime' =>$v1['finishTime'] != 0  ? date("Y-m-d H:i:s", (int)($v1['finishTime'] / 1000)) : null,
                'settleTime' => $v1['payMonth'] != 0 ? substr($v1['payMonth'], 0, 4) . '-' . substr($v1['payMonth'], 4, 2) . '-' . substr($v1['payMonth'], -2) . ' 00:00:00' : null,
                'isPunish' => ($v1['validCode'] == 13) ? true : false,    //是否是违规订单
            ];
            if($order_status != 1){
                $responseMsgResult[] = $turnData;
            }
        }
        return $responseMsgResult;
    }



    /**
     * 京东订单拉取
     * https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.order.query
     */
    public function getOrder($start_time, $time_type = 'day', $type="addOrderTime", $page = 1, &$responseMsgDataResult = [])
    {
//        $start_time = "2022-07-20 15:30:00";
        if ($time_type == 'day') {
            $start_time = date("Ymd", strtotime($start_time));
        }
        if ($time_type == 'hour') {
            $start_time = date("YmdH", strtotime($start_time));
        }
        if ($time_type == 'min') {
            $start_time = date("YmdHi", strtotime($start_time));
        }
        $method = 'jd.union.open.order.query';
        $h_params['pageNo'] = $page;
        $h_params['pageSize'] = 100;
        $h_params['type'] = $type == 'addOrderTime' ? 1 : 3;//'3';
        $h_params['time'] = $start_time;//$start_time;// 202201181919 202201181551 $start_time
        $params = json_encode(['orderReq' => $h_params]);
        $responseMsg = $this->public_query($method, $params);
        if(!isset($responseMsg['jd_union_open_order_query_response']) || !isset($responseMsg['jd_union_open_order_query_response']['code']) || !isset($responseMsg['jd_union_open_order_query_response']['result'])){
            return [];
        }
        if ($responseMsg['jd_union_open_order_query_response']['code'] == 0) {
            $responseMsgData = json_decode($responseMsg['jd_union_open_order_query_response']['result'], true);
            if (array_key_exists('data', $responseMsgData)) {
                if(empty($responseMsgDataResult)){
                    $responseMsgDataResult = $responseMsgData['data'];
                }else{
                    $responseMsgDataResult = array_merge($responseMsgDataResult, $responseMsgData['data']);
                    if ($responseMsgData['hasMore']) {
                        $this->getOrder($start_time, $time_type, $type, $page + 1, $responseMsgDataResult);
                    }
                }
            }
        }
//        $write       = json_encode($responseMsgDataResult);
//        $create_file = BASE_PATH."/runtime/jd.log";       //创建文件
//        file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
        return $this->returnOrderDeal($responseMsgDataResult);
    }


    /**
     * 猜你喜欢
     */
    public function guess_like($params){
        $mothed                 = 'jd.union.open.goods.material.query';
        $h_params['eliteId'] = 1;
        $h_params['subUnionId'] = $params['user_id'];
        $h_params['pageIndex']  = isset($params['page']) ? $params['page'] : 1;
        $h_params['pageSize']  = isset($params['pageSize']) ? $params['pageSize'] : 10;
        $h_params['userIdType'] = 8;
        $h_params['userId'] = isset($params['imei_full']) ? $params['imei_full'] : $params['imei'];
        ksort($h_params);
        $params = json_encode(['goodsReq' => $h_params]);
        $res    = $this->public_query($mothed, $params);
        if(isset($res['jd_union_open_goods_material_query_response']['result'])){
            $res = json_decode($res['jd_union_open_goods_material_query_response']['result'],true);
            if($res['code']==200){
                $result = $this->trun_list($res['data'], $code = 2);
                return ['status'=>true,'msg'=>'获取成功','data'=>$result];
            }else{
                return ['status'=>false,'msg'=>'','data'=>[]];
            }
        }else{
            return ['status'=>false,'msg'=>'','data'=>[]];
        }
    }


    /**
     * @param $user_id 用户id
     * @param $goods_id 商品id
     * @return array
     */
    public function intellectCreateturn($user_id, $url)
    {
        $mothed                 = 'jd.union.open.promotion.bysubunionid.get';
        $h_params['materialId'] = $url;
        $h_params['subUnionId'] = $user_id;
        $h_params['chainType']  = 2;
        ksort($h_params);
        $params = json_encode(['promotionCodeReq' => $h_params]);
        $res    = $this->public_query($mothed, $params);
        if ($res['jd_union_open_promotion_bysubunionid_get_response']['code'] == 0) {
            $ret = json_decode($res['jd_union_open_promotion_bysubunionid_get_response']['result']);
            if ($ret->code == 200) {
                return ['status' => true, 'msg' => $ret->data->clickURL, 'short_url' => $ret->data->shortURL];
            } else {
                return ['status' => false, 'msg' => $ret->message];
            }
        } else {
            return ['status' => false, 'msg' => '请求失败'];
        }
    }

    
    
    /**
     * 京东短连接 转商品id  订单侠
     */
    public function short_url_to_goodsid($url){
        $url="http://api.tbk.dingdanxia.com/jd/get_jd_skuid?apikey={$this->union['ddxAppKey']}&url={$url}";
        $retulst = json_decode(file_get_contents($url),true);
        if($retulst['code'] == 200){
            return ['code'=>true,'data'=>$retulst['data']];
        }else{
            return ['code'=>false,'msg'=>$retulst['msg']];
        }

    }

}
